<template>
	<view class="page">
		<view class="map-container">
			<map :longitude="longitude" :latitude="latitude" :markers="markers" :circles="circles"
				style="width: 100%; height: 100%;" :scale="20">
			</map>
		</view>
		<view class="status-card">
			<view class="distance-info">
				<text class="label">距离签到点:</text>
				<text class="value">{{ calculateDistance() }}米</text>
			</view>
			<view class="status-message" :class="statusClass">{{ statusMessage }}</view>
		</view>
		
		<!-- 签到按钮 -->
		<view class="card" v-if="!hasSigned">
			<button class="btn" :disabled="isDisabled" :class="{'btn-disabled': isDisabled, 'btn-primary': !isDisabled}"
				@click="handleCheckIn">{{ btnText }}</button>
		</view>
		
		<!-- 已签到后显示开始工作按钮 -->
		<view class="card" v-if="hasSigned">
			<button class="btn btn-work" :disabled="isWorking" :class="{'btn-disabled': isWorking, 'btn-success': !isWorking}"
				@click="startWork">{{ isWorking ? '工作中...' : '开始工作' }}</button>
		</view>
		
		<!-- 工作模式下的日志面板 -->
		<view class="log-panel" v-if="isWorking">
			<view class="log-header">
				<text class="log-title">位置更新日志</text>
				<text class="log-subtitle">每30秒自动更新一次</text>
			</view>
			<scroll-view scroll-y class="log-content" :scroll-top="scrollTop">
				<view v-for="(log, index) in locationLogs" :key="index" class="log-item">
					<text class="log-time">{{ log.time }}</text>
					<text class="log-message" :class="{'log-success': log.success, 'log-error': !log.success}">
						{{ log.message }}
					</text>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import request from '@/utils/request.js';
	export default {
		data() {
			return {
				lessonId: null,
				latitude: 0, // 当前位置纬度
				longitude: 0, // 当前位置经度
				markers: [], // 签到点标记
				circles: [],
				isCheckingIn: false, // 是否正在签到
				isDisabled: false, // 是否禁用按钮
				btnText: '签到', // 按钮文本
				checkInDistance: 100, // 签到距离阈值，调整为更合理的值
				checkInLocation: { // 签到点经纬度
					longitude: 0,
					latitude: 0
				},
				statusMessage: '正在获取位置...',
				statusClass: '',
				hasSigned: false, // 是否已签到
				isWorking: false, // 是否处于工作模式
				locationLogs: [], // 位置更新日志
				locationTimer: null, // 定时器
				scrollTop: 0 // 日志滚动位置
			}
		},
		mounted() {
			this.getLocation();
		},
		onLoad(option) {
			console.log('option:', option);
			this.lessonId = option.lessonId - 0;
		},
		onUnload() {
			// 页面卸载时清除定时器
			this.stopLocationUpdates();
		},
		methods: {
			getDetail() {
				request.post(`/lesson/detail?lessonId=${this.lessonId}`)
					.then(res => {
						let lesson = res.data;
						this.checkInLocation.longitude = lesson.signLocationLong;
						this.checkInLocation.latitude = lesson.signLocationLat;
						console.log('checkInLocation:', this.checkInLocation);
						
						// 检查签到点坐标是否有效
						if (!this.checkInLocation.longitude || !this.checkInLocation.latitude) {
							this.statusMessage = '签到点坐标无效，请联系管理员';
							this.statusClass = 'error';
							this.disableBtn('无法签到');
							return;
						}
						
						this.hasSigned = lesson.hasSigned;
						if (this.hasSigned) {
							this.disableBtn('已签到');
							this.statusMessage = '您已完成签到';
							this.statusClass = 'success';
						} else {
							// 计算距离并更新状态
							this.updateDistanceStatus();
						}

						this.initMarkers();
					})
					.catch(err => {
						console.error('获取课程详情失败:', err);
						this.statusMessage = '获取课程信息失败';
						this.statusClass = 'error';
					});
			},
			// 获取当前位置
			getLocation() {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						console.log('获取当前定位的返回内容:', res);
						const {
							latitude,
							longitude
						} = res;
						this.latitude = latitude;
						this.longitude = longitude;
						this.initMarkers();
						this.getDetail();
					},
					fail: (err) => {
						console.error('获取位置失败:', err);
						this.statusMessage = '获取位置失败，请检查定位权限';
						this.statusClass = 'error';
						this.disableBtn('无法签到');
					}
				});
			},
			// 初始化签到点标记
			initMarkers() {
				this.markers = [];
				this.circles = [];
				const {
					longitude,
					latitude
				} = this.checkInLocation;
				
				// 只有当签到点坐标有效时才添加标记
				if (longitude && latitude) {
					this.markers.push({
						id: 1,
						longitude,
						latitude,
						content: '签到点',
						iconPath: '/static/location.png',
						width: 30,
						height: 30
					});
					this.circles.push({
						longitude: longitude,
						latitude: latitude,
						radius: this.checkInDistance,
						fillColor: '#fafafa6A',
						color: '#00aaff'
					});
				}
				
				// 只有当当前位置有效时才添加标记
				if (this.longitude && this.latitude) {
					this.markers.push({
						id: 2,
						longitude: this.longitude,
						latitude: this.latitude,
						content: '当前位置',
						iconPath: '/static/location2.png',
						width: 30,
						height: 30
					});
				}
				
				console.log('签到点:', longitude, latitude);
				console.log('当前位置:', this.longitude, this.latitude);
			},
			// 计算当前位置与签到点距离
			getDistance() {
				const {
					longitude: lng1,
					latitude: lat1
				} = this.checkInLocation;
				const {
					longitude: lng2,
					latitude: lat2
				} = this;
				
				// 检查坐标是否有效
				if (!lng1 || !lat1 || !lng2 || !lat2) {
					console.error('坐标无效，无法计算距离');
					return Infinity; // 返回无限大表示无法计算
				}
				
				const radLat1 = lat1 * Math.PI / 180.0;
				const radLat2 = lat2 * Math.PI / 180.0;
				const a = radLat1 - radLat2;
				const b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
				let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math
					.pow(Math.sin(b / 2), 2)));
				s *= 6378.137;
				s = Math.round(s * 10000) / 10;
				return s;
			},
			// 计算并返回格式化的距离，用于显示
			calculateDistance() {
				const distance = this.getDistance();
				return distance === Infinity ? '未知' : distance;
			},
			// 更新距离状态信息
			updateDistanceStatus() {
				const distance = this.getDistance();
				if (distance === Infinity) {
					this.statusMessage = '无法计算距离';
					this.statusClass = 'warning';
					return;
				}
				
				if (distance > this.checkInDistance) {
					this.statusMessage = `距离过远，请靠近签到点`;
					this.statusClass = 'warning';
				} else {
					this.statusMessage = '您已在签到范围内';
					this.statusClass = 'success';
				}
			},
			disableBtn(text) {
				this.btnText = text;
				this.isDisabled = true;
				this.isCheckingIn = false;
			},
			// 处理签到按钮点击事件
			handleCheckIn() {
				if (this.isCheckingIn || this.isDisabled) {
					// 正在签到或者已经打过卡了，无需处理
					return;
				}
				
				this.isCheckingIn = true;
				this.btnText = '签到中...';
				
				// 重新获取当前位置，确保位置准确
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						const { latitude, longitude } = res;
						this.latitude = latitude;
						this.longitude = longitude;
						this.initMarkers();
						
						const distance = this.getDistance();
						if (distance > this.checkInDistance) {
							// 超过签到距离阈值，无法签到
							this.disableBtn('无法签到');
							this.statusMessage = '距离过远，无法签到';
							this.statusClass = 'error';
							
							uni.showToast({
								title: '距离签到点太远',
								icon: 'none'
							});
						} else {
							// 发送签到请求
							request.post("/sign/signWithLocation", {
									lng: this.longitude,
									lat: this.latitude,
									lessonId: this.lessonId
								})
								.then(res => {
									if (res.success) {
										// 签到成功
										this.hasSigned = true;
										this.statusMessage = '签到成功';
										this.statusClass = 'success';
										
										uni.showToast({
											title: '签到成功',
											icon: 'success'
										});
									} else {
										// 签到失败
										this.disableBtn('签到失败');
										this.statusMessage = res.message || '签到失败';
										this.statusClass = 'error';
										
										uni.showToast({
											title: res.message || '签到失败',
											icon: 'none'
										});
									}
								})
								.catch(err => {
									console.error('签到请求失败:', err);
									this.disableBtn('签到失败');
									this.statusMessage = '网络请求失败';
									this.statusClass = 'error';
									
									uni.showToast({
										title: '网络请求失败',
										icon: 'none'
									});
								});
						}
					},
					fail: (err) => {
						console.error('获取位置失败:', err);
						this.disableBtn('无法签到');
						this.statusMessage = '获取位置失败';
						this.statusClass = 'error';
						
						uni.showToast({
							title: '获取位置失败',
							icon: 'none'
						});
					}
				});
			},
			// 开始工作模式
			startWork() {
				if (this.isWorking) return;
				
				this.isWorking = true;
				uni.showToast({
					title: '工作模式已启动',
					icon: 'success'
				});
				
				// 导航到工作页面
				uni.navigateTo({
					url: `/pages/work_mode/work_mode?lessonId=${this.lessonId}&lat=${this.checkInLocation.latitude}&lng=${this.checkInLocation.longitude}`,
					fail: (err) => {
						console.error('导航到工作页面失败:', err);
						this.isWorking = false;
						
						// 如果导航失败，则在当前页面启动位置更新
						this.startLocationUpdates();
					}
				});
			},
			// 开始定期更新位置
			startLocationUpdates() {
				// 添加初始日志
				this.addLog('工作模式已启动，开始定期更新位置', true);
				
				// 立即更新一次位置
				this.updateLocation();
				
				// 设置定时器，每30秒更新一次位置
				this.locationTimer = setInterval(() => {
					this.updateLocation();
				}, 30000);
			},
			// 停止位置更新
			stopLocationUpdates() {
				if (this.locationTimer) {
					clearInterval(this.locationTimer);
					this.locationTimer = null;
					this.addLog('工作模式已停止', true);
				}
			},
			// 更新位置并发送到服务器
			updateLocation() {
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						const { latitude, longitude } = res;
						this.latitude = latitude;
						this.longitude = longitude;
						this.initMarkers();
						
						// 发送位置到服务器
						request.post("/work/updateLocation", {
							lng: longitude,
							lat: latitude,
							lessonId: this.lessonId
						})
						.then(res => {
							if (res.success) {
								this.addLog('位置已更新', true);
							} else {
								this.addLog(res.message || '位置更新失败', false);
							}
						})
						.catch(err => {
							console.error('位置更新请求失败:', err);
							this.addLog('网络请求失败', false);
						});
					},
					fail: (err) => {
						console.error('获取位置失败:', err);
						this.addLog('获取位置失败', false);
					}
				});
			},
			// 添加日志
			addLog(message, success = true) {
				const now = new Date();
				const time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
				
				this.locationLogs.push({
					time,
					message,
					success
				});
				
				// 限制日志数量，保留最新的50条
				if (this.locationLogs.length > 50) {
					this.locationLogs.shift();
				}
				
				// 滚动到底部
				this.$nextTick(() => {
					this.scrollTop = 9999;
				});
			}
		}
	}
</script>

<style>
	.page {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}

	.map-container {
		flex: 1;
		position: relative;
		overflow: hidden;
		border-radius: 0 0 20rpx 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.status-card {
		margin: 20rpx;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.distance-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10rpx;
	}

	.label {
		font-size: 28rpx;
		color: #666;
	}

	.value {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
	}

	.status-message {
		font-size: 30rpx;
		text-align: center;
		padding: 10rpx;
		border-radius: 6rpx;
	}

	.success {
		color: #52c41a;
		background-color: #f6ffed;
	}

	.warning {
		color: #faad14;
		background-color: #fffbe6;
	}

	.error {
		color: #f5222d;
		background-color: #fff1f0;
	}

	.card {
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 20rpx;
	}

	.btn {
		width: 80%;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		color: #fff;
		border-radius: 44rpx;
		font-size: 32rpx;
		font-weight: 500;
		transition: all .3s ease;
		box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
	}

	.btn-primary {
		background: linear-gradient(to right, #4f99ff, #6ba6ff);
	}
	
	.btn-success {
		background: linear-gradient(to right, #52c41a, #73d13d);
	}
	
	.btn-primary:active, .btn-success:active {
		transform: scale(0.98);
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.btn-disabled {
		background-color: #ccc;
		cursor: default;
		box-shadow: none;
	}
	
	.log-panel {
		margin: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		max-height: 300rpx;
		overflow: hidden;
	}
	
	.log-header {
		padding: 16rpx 20rpx;
		border-bottom: 1px solid #f0f0f0;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.log-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #333;
	}
	
	.log-subtitle {
		font-size: 24rpx;
		color: #999;
	}
	
	.log-content {
		padding: 10rpx 20rpx;
		max-height: 240rpx;
	}
	
	.log-item {
		display: flex;
		padding: 8rpx 0;
		font-size: 24rpx;
	}
	
	.log-time {
		color: #999;
		margin-right: 10rpx;
		flex-shrink: 0;
	}
	
	.log-message {
		flex: 1;
	}
	
	.log-success {
		color: #52c41a;
	}
	
	.log-error {
		color: #f5222d;
	}
</style>